const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');

async function resetAdminPassword() {
  try {
    // 创建数据库连接
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || 'asset_management'
    });

    // 生成新密码的哈希
    const newPassword = 'admin123';
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(newPassword, saltRounds);

    // 更新admin用户密码
    const [result] = await connection.execute(
      'UPDATE users SET password = ? WHERE username = ?',
      [hashedPassword, 'admin']
    );

    if (result.affectedRows > 0) {
      console.log('Admin密码重置成功！');
      console.log('用户名: admin');
      console.log('密码: admin123');
    } else {
      console.log('未找到admin用户，正在创建...');
      
      // 创建admin用户
      await connection.execute(
        'INSERT INTO users (username, password, email, name, role, created_at) VALUES (?, ?, ?, ?, ?, NOW())',
        ['admin', hashedPassword, 'admin@system.com', '系统管理员', 'admin']
      );
      
      console.log('Admin用户创建成功！');
      console.log('用户名: admin');
      console.log('密码: admin123');
    }

    await connection.end();
  } catch (error) {
    console.error('重置密码失败:', error.message);
  }
}

resetAdminPassword();
